package com.example.workmanager

import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.Observer
import androidx.work.*
import kotlinx.android.synthetic.main.activity_main.*
//键
const val INPUT_DATA_KEY = "input_data_key"
const val OUTPUT_DATA_KEY = "output_data_key"
//值
const val WORK_A_NAME = "work A"
const val WORK_B_NAME = "work B"

//缓存文件的名称
const val SHARED_PREFERENCEES_NAME = "shp_name"
//SharedPreferences.OnSharedPreferenceChangeListener
// 监听缓存中数据的变化
class MainActivity : AppCompatActivity(),SharedPreferences.OnSharedPreferenceChangeListener {
    //获得WorkManager的引用
    private val workManager = WorkManager.getInstance(this)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //注册缓存中数据变化的监听
        val sp = getSharedPreferences(SHARED_PREFERENCEES_NAME,Context.MODE_PRIVATE)
        sp.registerOnSharedPreferenceChangeListener(this)
        //更新界面数据
        updateView()

        button.setOnClickListener {
            val workRequestA = createWork(WORK_A_NAME)
            val workRequestB = createWork(WORK_B_NAME)

            workManager.beginWith(workRequestA)
                .then(workRequestB)
                //将需要在后台完成的工作加入到队列
                .enqueue()
            //通过观察获取后台传递给前台的数据
//            workManager.getWorkInfoByIdLiveData(workRequest.id).observe(this, Observer {
//                //it.state为三种状态：ENQUEUED，RUNNING，SUCCEEDED
//                Log.d("hello","onCreate:${(it.state)}")
//                //如果返回状态信息为SUCCEEDED，则打印后台传递给前台的数据
//                if(it.state == WorkInfo.State.SUCCEEDED){
//                    Log.d("hello","onCreate:${(it.outputData.getString(OUTPUT_DATA_KEY))}")
//                }
//            })
        }
    }

    private fun createWork(name: String): OneTimeWorkRequest {
        //约束条件,网络连接的时候才启动
        var constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build()

        /**
         * 解决OneTimeWorkRequestBuilder出现红色在依赖中添加
        kotlinOptions{
        jvmTarget = 1.8
        }可以解决
         */
        //单次请求
        return OneTimeWorkRequestBuilder<MyWorker>()
            //添加约束条件
            .setConstraints(constraints)
            //向后台传递少量的数据
            .setInputData(workDataOf(INPUT_DATA_KEY to name))
            .build()
    }

    /**
     * 更新界面数据，将缓存中的数据更新到界面
     */
    private fun updateView(){
        //获得缓存名为SHARED_PREFERENCEES_NAME的实例
        val sp = getSharedPreferences(SHARED_PREFERENCEES_NAME,Context.MODE_PRIVATE)

        textViewA.text = sp.getInt(WORK_A_NAME,0).toString()
        textViewB.text = sp.getInt(WORK_B_NAME,0).toString()
    }

    //监听缓存中数据的变化
    override fun onSharedPreferenceChanged(p0: SharedPreferences?, p1: String?) {
        updateView()
    }
}
